<script setup lang="ts">
import { ref } from 'vue'
import { checkMobile } from '@/utils/validate'
import type { FormInstance } from 'element-plus'
import { addUserApi } from '@/api/user'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
const router = useRouter()

const userinfo = ref({
  username: '',
  password: '',
  mobile: '',
})
const addUserRef = ref<FormInstance>()

const userinfoRules = {
  // 1.用户名必填
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  // 2.密码必填，长度在6~16位之间
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, max: 16, message: '长度应在6~16位之间', trigger: 'blur' },
  ],
  // 3.手机号校验
  // 1:rules 校验信息 无用
  // 2.value 填写表单数据
  // 3.callback:  不管成功还是失败都要调用callback
  // 3.1  成功：callback
  // 3.2  失败：callback(new Error(失败信息))
  mobile: [
    {
      validator: (rules: object, value: string, callback: (params?: object) => void) => {
        if (checkMobile(value)) {
          callback()
        } else {
          callback(new Error('手机号不合法'))
        }
      },
      trigger: 'blur',
    },
  ],
}

const onSubmit = () => {
  addUserRef.value!.validate(async (valid) => {
    if (!valid) return

    const res = await addUserApi(userinfo.value)
    if (res.data.state !== 201) {
      ElMessage.error('新增用户失败')
      return
    }
    router.push('/user')
  })
}

const onReset = () => {
  addUserRef.value?.resetFields()
}
</script>

<template>
  <el-card class="box-card">
    <template #header>
      <span>用户创建</span>
    </template>

    <el-form
      :model="userinfo"
      :rules="userinfoRules"
      ref="addUserRef"
      label-width="auto"
      size="large"
    >
      <el-form-item label="用户名" prop="username">
        <el-input placeholder="请输入用户名" v-model="userinfo.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input placeholder="请输入密码" v-model="userinfo.password"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input placeholder="请输入手机号" v-model="userinfo.mobile"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即创建</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped></style>
